package com.chat.demo.userservice;

import com.chat.demo.userservice.DTO.message.PrivateMessageDTO;
import com.chat.demo.userservice.DTO.message.GroupMessageDTO;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Component;

@Component
public class WebSocketSender {

    private final SimpMessagingTemplate messagingTemplate;

    public WebSocketSender(SimpMessagingTemplate messagingTemplate) {
        this.messagingTemplate = messagingTemplate;
    }

    public void sendMessageToUser(Long userId, PrivateMessageDTO message) {
        String userDestination = "/queue/messages";
        String fullDestination = "/user/" + userId + userDestination;

        System.out.println("📤 正在推送消息至: " + fullDestination);
        messagingTemplate.convertAndSendToUser(
                userId.toString(),   // Spring 会自动处理成 /user/{userId}/queue/messages
                userDestination,     // 实际目的地是 /queue/messages
                message
        );

        System.out.println("✅ 已发送消息给用户: " + userId);
    }

    public void broadcastMessageToGroup(int groupId, GroupMessageDTO message) {
        String destination = "/topic/group." + groupId;
        messagingTemplate.convertAndSend(destination, message);
        System.out.println("📢 广播消息至群组: " + destination);
    }
}